<template>
    <view class="comm-list-container">
        <!-- 使用封装的页面头部组件 -->
        <page-header title="植保管理"></page-header>

        <view class="search-box">
            <uni-search-bar
                placeholder="请输入要搜索的内容"
                v-model="searchKey"
                @confirm="handleSearch"
                @input="handleSearch"
                :radius="100"
                cancelButton="none" />
        </view>

        <view class="list-filter-container">
            <view class="filter-picker" @click="openDatePopup">
                <text class="picker-label">{{ selectedTime || '时间' }}</text>
                <text class="picker-arrow">
                    <roc-icon-plus
                        type="fas"
                        name="angle-down"
                        :size="16"
                        color="#2E6140"></roc-icon-plus>
                </text>
            </view>
            <picker
                mode="selector"
                :range="protectionTypeOptions"
                range-key="name"
                @change="onProtectionTypeChange">
                <view class="filter-picker">
                    <text class="picker-label">
                        {{ selectedProtectionType?.name || '植保类型' }}
                    </text>
                    <text class="picker-arrow">
                        <roc-icon-plus
                            type="fas"
                            name="angle-down"
                            :size="16"
                            color="#2E6140"></roc-icon-plus>
                    </text>
                </view>
            </picker>
            <picker
                mode="selector"
                :range="areaOptions"
                range-key="name"
                :value="selectedAreaIndex"
                @change="onAreaChange">
                <view class="filter-picker">
                    <text class="picker-label">
                        {{ areaOptions[selectedAreaIndex]?.name || '地块' }}
                    </text>
                    <text class="picker-arrow">
                        <roc-icon-plus
                            type="fas"
                            name="angle-down"
                            :size="16"
                            color="#2E6140"></roc-icon-plus>
                    </text>
                </view>
            </picker>
        </view>

        <!-- 日期选择弹出层 -->
        <uni-popup ref="datePopup" type="center">
            <view class="popup-content">
                <view class="popup-title">选择日期范围</view>
                <view class="date-picker-container">
                    <view class="date-item">
                        <text>开始日期：</text>
                        <picker
                            mode="date"
                            :value="tempStartDate || startDate"
                            @change="onStartDateChange">
                            <view class="picker-value">
                                {{ tempStartDate || startDate || '请选择' }}
                            </view>
                        </picker>
                    </view>
                    <view class="date-item">
                        <text>结束日期：</text>
                        <picker
                            mode="date"
                            :value="tempEndDate || endDate"
                            :start="tempStartDate || startDate"
                            @change="onEndDateChange">
                            <view class="picker-value">
                                {{ tempEndDate || endDate || '请选择' }}
                            </view>
                        </picker>
                    </view>
                </view>
                <view class="popup-buttons">
                    <button class="btn cancel" @click="cancelDatePicker">取消</button>
                    <button class="btn confirm" @click="confirmDatePicker">确定</button>
                </view>
            </view>
        </uni-popup>

        <view class="comm-record-list">
            <record-item
                v-for="(item, index) in filteredRecords"
                :key="index"
                :item="item"
                @clickItem="viewDetail(item)"
                @edit="editRecord(item)"
                @delete="confirmDelete(item)">
                <template #header>
                    <view class="item-header">
                        <view class="header-content">
                            <text class="date-title">{{ item.plotName }}-{{ item.fieldName }}</text>
                        </view>
                        <!-- <text class="date-text">{{ formatDate(item.startDate) }} 至 {{ formatDate(item.endDate) }}</text> -->
                    </view>
                </template>

                <template #content>
                    <view class="item-content">
                        <view class="info-row">
                            <text class="info-label">植保类型</text>
                            <text class="info-value">
                                {{ getProtectionTypeText(item.protectionType) }}
                            </text>
                        </view>

                        <view class="info-row">
                            <text class="info-label">施药时间</text>
                            <text class="info-value">
                                {{ formatDate(item.startDate) }} 至 {{ formatDate(item.endDate) }}
                            </text>
                        </view>

                        <view class="info-columns">
                            <view class="info-column">
                                <text class="column-label">植保面积</text>
                                <text class="column-value">{{ item.area || 0 }} 亩</text>
                            </view>

                            <view class="info-column">
                                <text class="column-label">施药方式</text>
                                <text class="column-value">
                                    {{ getApplicationMethodText(item.applicationMethod) }}
                                </text>
                            </view>
                            <view class="info-column">
                                <text class="column-label">用药信息</text>
                                <text class="column-value">{{ getMedicineInfo(item) }}</text>
                            </view>
                            <view class="info-column">
                                <text class="column-label">用量</text>
                                <text class="column-value">{{ getMedicineInfo2(item) }}</text>
                            </view>
                            <view class="info-column">
                                <text class="column-label">亩均</text>
                                <text class="column-value">{{ calculatePerMu(item) }}</text>
                            </view>
                        </view>
                        <view class="info-row">
                            <text class="info-label">备注</text>
                            <text class="info-value">{{ item.remark }}</text>
                        </view>
                        <view class="item-images" v-if="item.image">
                            <image
                                v-for="(img, imgIndex) in formatImages(item.image).slice(0, 3)"
                                :key="imgIndex"
                                :src="img"
                                mode="aspectFit"></image>
                        </view>
                    </view>
                </template>
            </record-item>

            <!-- 加载更多提示 -->
            <view class="load-more-container" v-if="filteredRecords.length > 0">
                <view v-if="loadingMore" class="loading-more">
                    <text class="loading-text">加载中...</text>
                </view>
                <view v-else-if="!hasMore" class="no-more">
                    <text class="no-more-text">没有更多数据了</text>
                </view>
            </view>
        </view>
        <!-- 无数据提示 -->
        <empty-data v-if="filteredRecords.length === 0 && !loading" />

        <view
            class="add-button"
            @click="navigateTo('/pages/agriculture/protectionManagement/addProtection')">
            <text class="add-icon">+</text>
        </view>
    </view>
</template>

<script>
import PageHeader from '@/components/PageHeader/index.vue'
import FilterTabs from '@/components/FilterTabs/index.vue'
import RecordItem from '@/components/RecordItem/index.vue'
import EmptyData from '@/components/EmptyData/index.vue'
import { protection } from '@/utils/api/index.js'
import { formatDate, formatImages } from '@/utils/util.js'
import { mapGetters, mapActions } from 'vuex'
import * as land from '@/utils/api/land.js'

export default {
    components: {
        PageHeader,
        FilterTabs,
        RecordItem,
        EmptyData,
    },
    data() {
        return {
            activeTab: 'all',
            searchKey: '',
            protectionRecords: [],
            loading: false,
            loadingMore: false, // 加载更多状态
            hasMore: true, // 是否还有更多数据
            pageParams: {
                pageNo: 1,
                pageSize: 30,
            },
            // 默认字典数据，当加载失败时使用
            protectionTypeDict: {
                1: '病害',
            },
            applicationMethodDict: {
                无人机: '无人机',
                农机: '农机',
                人工: '人工',
            },
            selectedTime: '',
            selectedProtectionType: '',
            selectedArea: '',
            timeOptions: ['最近7天', '本月', '自定义'],
            protectionTypeOptions: [],
            areaOptions: [{ id: 0, name: '选择地块' }],
            startDate: '',
            endDate: '',
            tempStartDate: '',
            tempEndDate: '',
            selectedAreaIndex: 0, // 新增，记录当前选中的下标
        }
    },
    computed: {
        ...mapGetters(['getDictByType', 'getDictLabel']),
        filteredRecords() {
            return this.protectionRecords
        },
    },
    onLoad() {
        // 加载字典数据
        this.loadDictData()
        this.fetchAreaOptions() // 新增
    },
    onShow() {
        this.fetchProtectionRecords()
    },
    // 下拉刷新
    onPullDownRefresh() {
        this.fetchProtectionRecords()
    },
    // 触底加载更多
    onReachBottom() {
        this.loadMoreData()
    },
    methods: {
        formatDate,
        formatImages,

        // 加载字典数据
        async loadDictData() {
            try {
                uni.showLoading({ title: '加载字典数据...' })

                // 加载植保类型字典
                const dictList = this.getDictByType('pests_diseases_weeds_type')
                this.protectionTypeOptions = dictList.map((item) => {
                    return {
                        name: item.label,
                        id: item.value,
                    }
                })
                console.log('')
                console.log('加载植保类型字典22:')
                console.log(dictList)
                console.log(this.protectionTypeOptions)

                uni.hideLoading()
            } catch (error) {
                console.error('加载字典数据失败:', error)
                uni.hideLoading()
                uni.showToast({
                    title: '加载字典数据失败',
                    icon: 'none',
                })
            }
        },

        // 将字典数据格式化为下拉选择框所需的格式
        formatDictToSelectData(dictType) {
            const dictList = this.getDictByType(dictType)
            return dictList.map((item) => ({
                value: item.value,
                text: item.label,
            }))
        },

        // 获取植保记录列表
        async fetchProtectionRecords(isLoadMore = false) {
            try {
                if (isLoadMore) {
                    this.loadingMore = true
                } else {
                    this.loading = true
                    uni.showLoading({ title: '加载中...' })
                }

                const res = await protection.getProtectionPage(this.pageParams)

                if (res.code === 0 && res.data) {
                    const newList = res.data.list || []

                    if (isLoadMore) {
                        // 加载更多时追加数据
                        this.protectionRecords = [...this.protectionRecords, ...newList]
                    } else {
                        // 首次加载或刷新时替换数据
                        this.protectionRecords = newList
                    }

                    // 判断是否还有更多数据
                    this.hasMore = newList.length >= this.pageParams.pageSize
                } else {
                    uni.showToast({
                        title: res.msg || '获取植保记录失败',
                        icon: 'none',
                    })
                }
            } catch (error) {
                console.error('获取植保记录失败', error)
                uni.showToast({
                    title: '获取植保记录失败',
                    icon: 'none',
                })
            } finally {
                this.loading = false
                this.loadingMore = false
                uni.hideLoading()
                uni.stopPullDownRefresh()
            }
        },

        // 搜索处理
        handleSearch() {
            // 重置页码
            this.pageParams.pageNo = 1
            this.hasMore = true // 重置加载更多状态

            // 设置搜索关键词
            if (this.searchKey) {
                this.pageParams.searchKey = this.searchKey
            } else {
                delete this.pageParams.searchKey
            }

            // 重新请求接口
            this.fetchProtectionRecords()
        },

        // 统一处理筛选变化
        handleFilterChange() {
            // 重置页码
            this.pageParams.pageNo = 1
            this.hasMore = true // 重置加载更多状态

            // 清除之前的筛选条件
            delete this.pageParams.startDate
            delete this.pageParams.endDate
            delete this.pageParams.protectionType
            delete this.pageParams.plotId

            // 时间筛选
            if (this.startDate && this.endDate) {
                this.pageParams.startDate = this.startDate
                this.pageParams.endDate = this.endDate
            }
            // 植保类型筛选
            if (this.selectedProtectionType && this.selectedProtectionType.id) {
                this.pageParams.protectionType = this.selectedProtectionType.id
            }
            // 地块筛选
            if (this.selectedArea) {
                this.pageParams.plotId = this.selectedArea
            }

            // 重新请求接口
            this.fetchProtectionRecords()
        },

        // 加载更多数据
        async loadMoreData() {
            if (this.loadingMore || !this.hasMore) {
                return
            }

            this.pageParams.pageNo += 1
            await this.fetchProtectionRecords(true)
        },

        // 查看详情
        viewDetail(item) {
            this.navigateTo(`/pages/agriculture/protectionManagement/addProtection?id=${item.id}`)
        },

        // 编辑记录
        editRecord(item) {
            this.navigateTo(`/pages/agriculture/protectionManagement/addProtection?id=${item.id}`)
        },

        // 确认删除
        confirmDelete(item) {
            uni.showModal({
                title: '确认删除',
                content: '确定要删除此植保记录吗？',
                success: (res) => {
                    if (res.confirm) {
                        this.deleteRecord(item.id)
                    }
                },
            })
        },

        // 删除记录
        async deleteRecord(id) {
            try {
                uni.showLoading({ title: '删除中...' })

                const res = await protection.deleteProtectionRecord(id)

                if (res.code === 0 && res.data) {
                    uni.showToast({
                        title: '删除成功',
                        icon: 'success',
                    })

                    // 重新加载列表
                    this.fetchProtectionRecords()
                } else {
                    uni.showToast({
                        title: res.msg || '删除失败',
                        icon: 'none',
                    })
                }
            } catch (error) {
                console.error('删除植保记录失败', error)
                uni.showToast({
                    title: '删除失败',
                    icon: 'none',
                })
            } finally {
                uni.hideLoading()
            }
        },

        // 页面跳转
        navigateTo(url) {
            uni.navigateTo({ url })
        },

        // 获取植保类型文本
        getProtectionTypeText(type) {
            if (!type) return '未知'

            // 尝试从字典获取
            const dictLabel = this.getDictLabel('pests_diseases_weeds_type', type)
            if (dictLabel) return dictLabel

            // 如果字典中没有，使用默认映射
            return this.protectionTypeDict[type] || type || '未知类型'
        },

        // 获取施药方式文本
        getApplicationMethodText(method) {
            if (!method) return '未知'

            // 尝试从字典获取
            const dictLabel = this.getDictLabel('application_method', method)
            if (dictLabel) return dictLabel

            // 如果字典中没有，使用默认映射
            return this.applicationMethodDict[method] || method || '未知方式'
        },
        // 获取获取用药信息文本
        getMedicineText(method) {
            console.log('获取获取用药信息文本')
            console.log(method)
            if (!method) return '未知'

            // 尝试从字典获取
            const dictLabel = this.getDictLabel('drug_type', method)
            console.log(dictLabel)
            if (dictLabel) return dictLabel

            return ''
        },

        // 获取用药信息
        getMedicineInfo(item) {
            if (item.listSubtable && item.listSubtable.length > 0) {
                const medicine = item.listSubtable[0]
                if (medicine.pesticideId && medicine.dosage) {
                    return `${this.getMedicineText(medicine.pesticideId)}`
                }
            }
            return '无用药信息'
        },
        // 获取用药信息  -用量
        getMedicineInfo2(item) {
            if (item.listSubtable && item.listSubtable.length > 0) {
                const medicine = item.listSubtable[0]
                if (medicine.pesticideId && medicine.dosage) {
                    return `${medicine.dosage}${medicine.dosageUnit || 'Kg'}`
                }
            }
            return '无用药信息'
        },
        // 计算亩均用量
        calculatePerMu(item) {
            if (item.listSubtable && item.listSubtable.length > 0 && item.area) {
                const medicine = item.listSubtable[0]
                if (medicine.pesticideId && medicine.dosage) {
                    const perMu = (medicine.dosage / item.area).toFixed(2)
                    return `${perMu}${medicine.dosageUnit || 'Kg'}`
                }
            }
            return '-'
        },
        onTimeChange(e) {
            const selected = this.timeOptions[e.detail.value]
            if (selected === '自定义') {
                this.$refs.datePopup.open()
            } else {
                this.selectedTime = selected
                // 根据选择的时间更新筛选条件
            }
        },
        onProtectionTypeChange(e) {
            const index = e.detail.value
            this.selectedProtectionType = this.protectionTypeOptions[index]
            this.handleFilterChange()
        },
        onAreaChange(e) {
            const index = e.detail.value
            this.selectedAreaIndex = index
            if (index > 0) {
                this.selectedArea = this.areaOptions[index].id // 选中的地块id
            } else {
                this.selectedArea = ''
            }
            this.handleFilterChange()
        },
        onStartDateChange(e) {
            this.tempStartDate = e.detail.value
            if (this.tempEndDate && this.tempEndDate < this.tempStartDate) {
                this.tempEndDate = ''
            }
        },
        onEndDateChange(e) {
            this.tempEndDate = e.detail.value
            if (this.tempStartDate && this.tempEndDate < this.tempStartDate) {
                uni.showToast({
                    title: '结束日期不能早于开始日期',
                    icon: 'none',
                })
                this.tempEndDate = this.tempStartDate
            }
        },
        confirmDatePicker() {
            if (this.tempStartDate && this.tempEndDate) {
                if (this.tempEndDate < this.tempStartDate) {
                    uni.showToast({
                        title: '结束日期不能早于开始日期',
                        icon: 'none',
                    })
                    return
                }
                this.startDate = this.tempStartDate
                this.endDate = this.tempEndDate
                this.selectedTime = `${this.startDate} 至 ${this.endDate}`
                this.$refs.datePopup.close()
                this.handleFilterChange()
            } else {
                uni.showToast({
                    title: '请选择开始和结束日期',
                    icon: 'none',
                })
            }
        },
        cancelDatePicker() {
            this.tempStartDate = this.startDate
            this.tempEndDate = this.endDate
            this.$refs.datePopup.close()
        },
        openDatePopup() {
            this.$refs.datePopup.open()
        },
        async fetchAreaOptions() {
            try {
                const res = await land.getAllParcelAndFields()
                if (res.code === 0 && res.data && res.data.length > 0) {
                    this.areaOptions = [
                        { id: 0, name: '选择地块' },
                        ...res.data.map((parcel) => ({
                            id: parcel.id,
                            name: parcel.parcelName,
                        })),
                    ]
                } else {
                    this.areaOptions = [{ id: 0, name: '选择地块' }]
                }
            } catch (e) {
                this.areaOptions = [{ id: 0, name: '选择地块' }]
            }
        },
    },
}
</script>

<style lang="scss" scoped>
.list-filter-container {
    display: flex;
    justify-content: space-between;
    padding: 10px;
}

.filter-picker {
    flex: 1;
    display: flex;
    align-items: center;
    justify-content: space-between;
    margin: 0 5px;
    padding: 10px 12px;
    background-color: #fff;
    border: 1px solid #e5e5e5;
    border-radius: 8px;
    font-size: 15px;
    color: #333;
    position: relative;
    min-width: 0;
    box-sizing: border-box;
}

.picker-label {
    flex: 1;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
    text-align: left;
}

.picker-arrow {
    margin-left: 8px;
    font-size: 13px;
    color: #999;
}

.picker {
    flex: 1;
    margin: 0 5px;
    padding: 10px;
    background-color: #f5f5f5;
    border-radius: 5px;
    text-align: center;
}

.popup-content {
    width: 600rpx;
    background-color: #ffffff;
    border-radius: 10px;
    padding: 20px;
}

.popup-title {
    font-size: 18px;
    font-weight: bold;
    text-align: center;
    margin-bottom: 20px;
}

.date-picker-container {
    margin-bottom: 20px;
}

.date-item {
    display: flex;
    align-items: center;
    margin-bottom: 10px;
}

.picker-value {
    flex: 1;
    border: 1px solid #ccc;
    border-radius: 5px;
    padding: 5px;
    text-align: center;
    width: 300rpx;
}

.popup-buttons {
    display: flex;
    justify-content: space-between;
}

.btn {
    flex: 1;
    margin: 0 5px;
    padding: 10px;
    border-radius: 5px;
    text-align: center;
    font-size: 16px;
}

.cancel {
    background-color: #f5f5f5;
    color: #333;
}

.confirm {
    background-color: #2e6140;
    color: #fff;
}

/* 加载更多样式 */
.load-more-container {
    padding: 20px;
    text-align: center;
}
</style>
